<template>
  <t-dialog
    v-model:visible="formVisible"
    :width="width ? width : '500px'"
    :header="title"
    :footer="false"
    destroyOnClose
  >
    <template #body>
      <t-form
        ref="form"
        :data="formData"
        :layout="layout ? layout : 'vertical'"
        :rules="rules"
        :label-width="120"
        @submit="onSubmit"
      >
        <slot :formData="formData"> </slot>
        <t-form-item v-if="hasSubmitButton" style="float: right">
          <t-button variant="outline" @click="onClickCloseBtn">取消</t-button>
          <t-button style="margin-left: 10px" theme="primary" type="submit" :loading="loading">确定</t-button>
        </t-form-item>
      </t-form>
    </template>
  </t-dialog>
</template>
<script setup lang="ts">
import { type SubmitContext, type Data, type FormRule, MessagePlugin } from 'tdesign-vue-next';
import { ref, watch } from 'vue';

const props = defineProps<{
  /** 默认数据 */
  INITIAL_DATA: Record<string, any>;
  /** 验证器 */
  rules?: Record<string, FormRule[]>;
  /** 标题 */
  title: string;
  /** 可视 */
  visible: boolean;
  /** 数据 */
  data: Record<string, any>;
  /** 请求 */
  post: (body: any) => Promise<boolean>;
  /** 宽度 */
  width?: string;
  /** 布局 */
  layout?: 'vertical' | 'inline';
}>();

// 是否显示底部按钮
const hasSubmitButton = ref(true);

watch(
  () => props.title,
  (title) => {
    // 如果是 "IP检测" 或 "流水详情"，则隐藏按钮
    hasSubmitButton.value = !['IP检测', '流水详情', '详情'].includes(title);
  },
  { immediate: true },
);

/** 关闭 */
const emit = defineEmits(['update:visible']);
const formVisible = ref(false);
const formData = ref({ ...props.INITIAL_DATA });
const loading = ref(false);

const onSubmit = async ({ validateResult, firstError }: SubmitContext<Data>) => {
  loading.value = true;
  if (!firstError) {
    try {
      await props.post({ data: formData.value });
      MessagePlugin.success('提交成功');
      formVisible.value = false;
    } catch (e: any) {
      // MessagePlugin.error(e.message);
    }
  } else {
    // console.log('Errors: ', validateResult);
    MessagePlugin.warning(firstError);
  }
  loading.value = false;
};

const onClickCloseBtn = () => {
  formVisible.value = false;
  formData.value = { ...props.INITIAL_DATA };
};

watch(
  () => formVisible.value,
  (val) => {
    emit('update:visible', val);
  },
);

watch(
  () => props.visible,
  (val) => {
    formVisible.value = val;
  },
);

watch(
  () => props.data,
  (val) => {
    formData.value = val;
  },
);
</script>
